﻿using System;
using System.Data;
using System.Linq;
using Common;
using Model;

namespace BLL
{
    public class Sys_Parameter_BLL
    {
        ExtendedDBModelContainer _db = new ExtendedDBModelContainer();

        public IQueryable<Sys_Parameter> Get()
        {
            return _db.Sys_Parameter.OrderBy(a => a.ParameterName);
        }

        public Sys_Parameter Get(Guid? Id)
        {
            var item = new Sys_Parameter();

            if (Id != null)
            {
                item = _db.Sys_Parameter.Single(a => a.Id.Equals(Id.Value));
            }
            return item;
        }

        public string Get(string ParameterName)
        {
            string parameters = "";
            var item = _db.Sys_Parameter.SingleOrDefault(a => a.ParameterName.Equals(ParameterName));
            if (item != null)
            {
                parameters = item.Parameters;
            }
            return parameters;
        }

        public void Save(Guid? Id, ref Sys_Parameter item)
        {
            ExtendedDBModelContainer _db = new ExtendedDBModelContainer();

            if (Id == null)
            {
                item.Id = Guid.NewGuid();
                _db.Sys_Parameter.AddObject(item);
            }
            else
            {
                _db.Sys_Parameter.Attach(item);
                _db.ObjectStateManager.ChangeObjectState(item, EntityState.Modified);
            }

            //是否加入 web.config
            if (item.WriteWebConfig)
            {
                ConfigurationOperator cop = new ConfigurationOperator(ConfigurationOperator.ConfigType.WebConfig);
                cop.AddAppSetting(item.ParameterName, item.Parameters);
                cop.Save();
            }

            _db.SaveChanges();
        }

        public void DeleteObject(Guid Id)
        {
            var item = new Sys_Parameter() { Id = Id };
            _db.Sys_Parameter.Attach(item);
            _db.ObjectStateManager.ChangeObjectState(item, EntityState.Deleted);
            _db.SaveChanges();
        }
    }
}
